package org.example.xsda.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.xsda.common.PageResult;
import org.example.xsda.entity.Classes;
import org.example.xsda.entity.Dept;
import org.example.xsda.entity.SysUser;
import org.example.xsda.exception.BusinessException;
import org.example.xsda.mapper.ClassesMapper;
import org.example.xsda.mapper.DeptMapper;
import org.example.xsda.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 班级服务
 */
@Slf4j
@Service
public class ClassService {

    @Autowired
    private ClassesMapper classesMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisService redisService;

    // 缓存key前缀
    private static final String CACHE_KEY_CLASS = "class:";
    private static final String CACHE_KEY_CLASS_LIST = "class:list:";

    /**
     * 分页查询班级
     */
    public PageResult<Classes> page(Long current, Long size, String keyword, Long deptId) {
        Page<Classes> page = new Page<>(current, size);
        LambdaQueryWrapper<Classes> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(Classes::getClassName, keyword)
                    .or().like(Classes::getClassCode, keyword));
        }
        if (deptId != null) {
            wrapper.eq(Classes::getDeptId, deptId);
        }
        wrapper.orderByDesc(Classes::getEnrollYear);
        
        Page<Classes> classPage = classesMapper.selectPage(page, wrapper);
        return new PageResult<>(classPage.getTotal(), classPage.getRecords(), classPage.getCurrent(), classPage.getSize());
    }

    /**
     * 获取所有班级（可按院系过滤，带缓存）
     */
    @SuppressWarnings("unchecked")
    public List<Classes> list(Long deptId) {
        String cacheKey = CACHE_KEY_CLASS_LIST + (deptId == null ? "all" : deptId);
        
        // 先从缓存中获取
        Object cached = redisService.get(cacheKey);
        if (cached != null) {
            log.debug("从缓存中获取班级列表：deptId={}", deptId);
            return (List<Classes>) cached;
        }
        
        // 缓存未命中，从数据库查询
        LambdaQueryWrapper<Classes> wrapper = new LambdaQueryWrapper<>();
        if (deptId != null) {
            wrapper.eq(Classes::getDeptId, deptId);
        }
        wrapper.orderByDesc(Classes::getEnrollYear);
        List<Classes> list = classesMapper.selectList(wrapper);
        
        // 存入缓存（1小时）
        redisService.set(cacheKey, list, 1, java.util.concurrent.TimeUnit.HOURS);
        log.debug("将班级列表存入缓存：deptId={}", deptId);
        
        return list;
    }

    /**
     * 根据ID获取班级（带缓存）
     */
    public Classes getById(Long id) {
        String cacheKey = CACHE_KEY_CLASS + id;
        
        // 先从缓存中获取
        Object cached = redisService.get(cacheKey);
        if (cached != null) {
            log.debug("从缓存中获取班级信息：id={}", id);
            return (Classes) cached;
        }
        
        // 缓存未命中，从数据库查询
        Classes classes = classesMapper.selectById(id);
        if (classes == null) {
            throw new BusinessException("班级不存在");
        }
        
        // 存入缓存（1小时）
        redisService.set(cacheKey, classes, 1, java.util.concurrent.TimeUnit.HOURS);
        log.debug("将班级信息存入缓存：id={}", id);
        
        return classes;
    }

    /**
     * 新增班级
     */
    public void add(Classes classes) {
        // 检查班级编码是否已存在
        LambdaQueryWrapper<Classes> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Classes::getClassCode, classes.getClassCode());
        Long count = classesMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException("班级编码已存在");
        }

        // 检查院系是否存在
        Dept dept = deptMapper.selectById(classes.getDeptId());
        if (dept == null) {
            throw new BusinessException("所属院系不存在");
        }

        // 检查班主任是否存在
        if (classes.getHeadTeacherId() != null) {
            SysUser teacher = sysUserMapper.selectById(classes.getHeadTeacherId());
            if (teacher == null || teacher.getRoleId() != 3) {
                throw new BusinessException("班主任不存在或角色不正确");
            }
        }

        classesMapper.insert(classes);
        
        // 清除班级列表缓存
        redisService.deleteByPattern(CACHE_KEY_CLASS_LIST);
        
        log.info("新增班级成功：{}", classes.getClassName());
    }

    /**
     * 更新班级
     */
    public void update(Classes classes) {
        Classes existClass = classesMapper.selectById(classes.getId());
        if (existClass == null) {
            throw new BusinessException("班级不存在");
        }

        // 检查班级编码是否重复
        LambdaQueryWrapper<Classes> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Classes::getClassCode, classes.getClassCode());
        wrapper.ne(Classes::getId, classes.getId());
        Long count = classesMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException("班级编码已存在");
        }

        classesMapper.updateById(classes);
        
        // 清除缓存
        redisService.delete(CACHE_KEY_CLASS + classes.getId());
        redisService.deleteByPattern(CACHE_KEY_CLASS_LIST);
        
        log.info("更新班级成功：{}", classes.getClassName());
    }

    /**
     * 删除班级
     */
    public void delete(Long id) {
        Classes classes = classesMapper.selectById(id);
        if (classes == null) {
            throw new BusinessException("班级不存在");
        }

        classesMapper.deleteById(id);
        
        // 清除缓存
        redisService.delete(CACHE_KEY_CLASS + id);
        redisService.deleteByPattern(CACHE_KEY_CLASS_LIST);
        
        log.info("删除班级成功：{}", classes.getClassName());
    }
}

